package com.orangelife.mobile.common.activity;

import android.os.Bundle;
import android.view.View;

import com.curry.android.adapter.FatherAdapter;
import com.curry.android.http.OrangeHttpConstant;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.DialogHelper;
import com.markupartist.android.widget.PullToRefreshListView;
import com.orangelife.mobile.common.view.EmptyLayout;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.surrounding.activity.SurroundingGoodListActivity;
import com.orangelife.mobile.util.ToastHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * 下拉刷新的基类
 * Created by wgf on 2016/3/24.
 *
 * @author wgf
 * @since v3.6.0
 */
public abstract class PullRefreshBaseActivity extends OrangeLifeBaseActivity {
    /** 一页中数据的条数，初始设置为8条 */
    protected int pageSize = 10;
    /** 初始页，初始化为第一页 */
    protected int pageNo = Constant.PAGE_NO_DEFAULT;
    /** 请求模式，上拉加载更多 */
    protected final int REQ_MODE_LOAD_MORE = 0;
    protected final int REQ_MODE_REFRESH = 1;
    protected final int REQ_MODE_INIT = 2;
    protected int currentReqMode = REQ_MODE_INIT;
    private String emptyMsg = "";
    private int emptyImg = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showProgress();
        requestWhenPullRefresh();
    }

    protected void setNoDataInfo(String emptyMsg, int emptyImg) {
        this.emptyMsg = emptyMsg;
        this.emptyImg = emptyImg;
    }

    protected void resetPageToDefault() {
        currentReqMode = REQ_MODE_INIT;
        pageSize = 10;
        pageNo = Constant.PAGE_NO_DEFAULT;
    }

    protected void setPageAfterDel() {
        pageSize = pageSize * pageNo;
        pageNo = Constant.PAGE_NO_DEFAULT;
    }

    protected void handleAfterRequest(int errCode, boolean hasNet, int total, List data, PullToRefreshListView pullListView, FatherAdapter adapter) {
        dismissProgress();
        if (!hasNet || VolleyHttpUtil.ERR_CODE_NET_EXCEPTION.equals(errCode + "") || data == null) {
            recoverPageNo();
            setEmptyLayoutErrorType(EmptyLayout.NETWORK_ERROR);
        } else if (VolleyHttpUtil.ERR_CODE_NET_EXCEPTION.equals(OrangeHttpConstant.ERRCODE_SYSTEM_ERROR)) {
            recoverPageNo();
            setEmptyLayoutErrorType(EmptyLayout.SERVER_ERROR);
        } else {
            updateListView(data, total, pullListView, adapter);
        }
    }

    private void recoverPageNo() {
        if (currentReqMode == REQ_MODE_LOAD_MORE && pageNo > Constant.PAGE_NO_DEFAULT) {
            pageNo--;/*如果没有网络，则上拉加载所增加的页数还原一页*/
        }
    }

    protected void handleAfterRequest(boolean hasNet, int total, List data, PullToRefreshListView pullListView, FatherAdapter adapter) {
        handleAfterRequest(-1, hasNet, total, data, pullListView, adapter);
    }

    protected abstract EmptyLayout getEmptyLayout();

    protected abstract List getData();

    protected abstract int getDataCount();

    protected abstract void requestWhenPullRefresh();

    protected void setXListViewAndEmptyLayoutListener(PullToRefreshListView pullListView, EmptyLayout emptyLayout, FatherAdapter adapter) {
        pullListView.setPullLoadEnable(false);
        pullListView.setAdapter(adapter);
        pullListView.setXListViewListener(new PullToRefreshListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                currentReqMode = REQ_MODE_REFRESH;
                showProgress();
                requestWhenPullRefresh();
            }

            @Override
            public void onLoadMore() {
                currentReqMode = REQ_MODE_LOAD_MORE;
                showProgress();
                requestWhenPullRefresh();
            }
        });
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getData() != null && getData().size() > 0) {
                    getData().clear();//由于弹出框样式和是否有数据有关，为了避免弹出对话框，清空数据
                }
                currentReqMode = REQ_MODE_INIT;
                showProgress();
                requestWhenPullRefresh();
            }
        });
    }

    protected void showProgress() {
        if (currentReqMode == REQ_MODE_LOAD_MORE) {
            pageNo += 1;
        } else if (currentReqMode == REQ_MODE_REFRESH) {/*之所以多此一举，主要为了可读性*/
            pageNo = Constant.PAGE_NO_DEFAULT;
        } else if (currentReqMode == REQ_MODE_INIT) {
            pageNo = Constant.PAGE_NO_DEFAULT;
            if (hasData()) {
                setEmptyLayoutErrorType(EmptyLayout.HIDE_LAYOUT);
                showDialog(this);
            } else {
                setEmptyLayoutErrorType(EmptyLayout.NETWORK_LOADING);
            }
        }
    }

    protected void dismissProgress() {
        if (currentReqMode == REQ_MODE_INIT) {
            if (hasData()) {
                DialogHelper.closeDialog(dialog);
            } else {
                dismissEmptyLayout();
            }
        }
    }

    private void updateListView(List list, int total, PullToRefreshListView pullListView, FatherAdapter adapter) {
        List refreshList = getData();
        if (getData() == null) {/*处理rl被置空的可能情况*/
            refreshList = new ArrayList<>();
        }
        if (currentReqMode == REQ_MODE_REFRESH) {
            pullListView.stopRefresh();
            refreshList.clear();
        } else if (currentReqMode == REQ_MODE_INIT) {
            refreshList.clear();
        } else {
            pullListView.stopLoadMore();
        }
        if (list == null || list.size() == 0) {
            if (currentReqMode == REQ_MODE_REFRESH || currentReqMode == REQ_MODE_INIT) {
                setEmptyLayoutErrorType(EmptyLayout.NODATA);
                if (getEmptyLayout() != null) {
                    if (emptyImg != 0) {
                        getEmptyLayout().setErrorImage(emptyImg);
                    }
                    if ("".equals(emptyMsg)) {
                        getEmptyLayout().setErrorMessage(emptyMsg);
                    }
                }

            }
            pullListView.setPullLoadEnable(false);
        } else {
            refreshList.addAll(list);
        }
        int count = getDataCount();
        if (count >= total) {
            if (currentReqMode == REQ_MODE_LOAD_MORE) {
                pullListView.setPullLoadEnable(false);
            } else {
                pullListView.setHideFooter();
            }
        } else {
            pullListView.setPullLoadEnable(true);
        }
        if (adapter != null) {
            adapter.setList(refreshList);
            adapter.notifyDataSetChanged();
        }
    }

    private boolean hasData() {
        return getData() != null && getData().size() > 0;
    }

    private void setEmptyLayoutErrorType(int errorType) {
        if (getEmptyLayout() != null) {
            getEmptyLayout().setErrorType(errorType);
        }
    }

    private void dismissEmptyLayout() {
        if (getEmptyLayout() != null) {
            getEmptyLayout().dismiss();
        }
    }
}
